package it.polimi.traveldream.ejb.invito;

import it.polimi.traveldream.ejb.acquistomanagement.Acquisto;
import it.polimi.traveldream.ejb.usermanagement.User;
import javax.annotation.Resource;
import javax.ejb.EJBContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class InvitoMgrBean implements InvitoMgr {

	@PersistenceContext
    private EntityManager em;
	
	@Resource
	private EJBContext context;

	@Override
	public void save(InvitoDTO nuovo, int idAcquisto) {
		Acquisto acquisto = em.find(Acquisto.class, idAcquisto);
		//int idPacchetto = acquisto.getPacchetto().getIdPacchetto();
		Invito newI = new Invito();
		newI.setAcquisto(acquisto);
		newI.setMittente(getPrincipalUser().getEmail());
		newI.setDestinatario(nuovo.getDestinatario());
		newI.setTesto(nuovo.getTesto());
		newI.setProdotto(acquisto.getPacchetto().getNome());
		em.persist(newI);
	}
	
	public User trova(String username){
		return em.find(User.class, username);
	}
	
	public User getPrincipalUser(){
		return trova(getPrincipalUsername());
	}
	
	public String getPrincipalUsername(){
		return context.getCallerPrincipal().getName();
	}
	
}
